package com.xh.imageeditor.sdk;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.xh.imageeditor.sdk.core.IMGMode;
import com.xh.imageeditor.sdk.core.IMGText;
import com.xh.imageeditor.sdk.core.util.BarUtils;
import com.xh.imageeditor.sdk.core.util.KeyboardUtils;
import com.xh.imageeditor.sdk.view.IMGColorGroup;
import com.xh.imageeditor.sdk.view.IMGView;

/**
 * Created by felix on 2017/12/5 下午3:08.
 */

abstract class IMGEditBaseActivity extends Activity implements View.OnClickListener,
        IMGTextEditDialog.Callback, RadioGroup.OnCheckedChangeListener,
        DialogInterface.OnShowListener, DialogInterface.OnDismissListener {

    protected IMGView mImgView;

    private RadioGroup mModeGroup;

    private IMGColorGroup mColorGroup;

    private IMGTextEditDialog mTextDialog;

    private View mLayoutOpSub;

    private ViewSwitcher mOpSwitcher;

    private static final int PERMISSION_REQUESTCODE = 1;
    private String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static final int OP_HIDE = -1;

    public static final int OP_NORMAL = 0;

    public static final int OP_CLIP = 1;

    public static final int OP_SUB_DOODLE = 0;

    public static final int OP_SUB_MOSAIC = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.transparentBar(getWindow()); //全屏布局拉到状态栏/导航栏，透明状态栏/导航栏
        if (permission()) {
            init();
        }
    }

    private void init() {
        Bitmap bitmap = getBitmap();
        if (bitmap != null) {
            setContentView(R.layout.image_edit_activity);
            initViews();
            mImgView.setImageBitmap(bitmap);
            onCreated();
        } else finish();
    }

    /**
     * 动态授权
     */
    private boolean permission() {
        boolean isPermission = true;
        for (int i = 1; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                isPermission = false;
                break;
            }
        }
        if (!isPermission) {
            //没有授权
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUESTCODE);
        }
        return isPermission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUESTCODE:
                StringBuilder text = new StringBuilder();
                boolean isPermission = true;
                for (int i = 1; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        isPermission = false;
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {//用户选择了禁止不再询问
                            if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                text.append("存储/");
                            }
                        }
                    }
                }
                if (isPermission) {
                    init();
                } else {
                    if (!TextUtils.isEmpty(text)) {
                        text.deleteCharAt(text.length()-1);
                        Toast.makeText(this, "请在应用权限打开 "+text+" 权限", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, "使用该功能需要存储权限", Toast.LENGTH_LONG).show();
                    }

                    finish();
                }
                break;
            default:
                break;
        }
    }

    public void onCreated() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        BarUtils.setStatusBarVisibility(getWindow(), false); //隐藏状态栏
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    private void initViews() {
        mImgView = findViewById(R.id.image_canvas);
        mModeGroup = findViewById(R.id.rg_modes);

        mOpSwitcher = findViewById(R.id.vs_op);

        mColorGroup = findViewById(R.id.cg_colors);
        mColorGroup.setOnCheckedChangeListener(this);

        mLayoutOpSub = findViewById(R.id.layout_op_sub);
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.rb_doodle) {
            onModeClick(IMGMode.DOODLE);
        } else if (vid == R.id.btn_text) {
            onTextModeClick();
        } else if (vid == R.id.rb_mosaic) {
            onModeClick(IMGMode.MOSAIC);
        } else if (vid == R.id.btn_clip) {
            onModeClick(IMGMode.CLIP);
        } else if (vid == R.id.btn_undo) {
            onUndoClick();
        } else if (vid == R.id.tv_done) {
            onDoneClick();
        } else if (vid == R.id.btn_cancel) {
            onCancelClick();
        } else if (vid == R.id.tv_clip_cancel) {
            onCancelClipClick();
        } else if (vid == R.id.tv_clip_done) {
            onDoneClipClick();
        } else if (vid == R.id.ib_clip_reset) {
            onResetClipClick();
        } else if (vid == R.id.ib_clip_rotate) {
            onRotateClipClick();
        }
    }

    public void updateModeUI() {
        IMGMode mode = mImgView.getMode();
        switch (mode) {
            case DOODLE:
                mModeGroup.check(R.id.rb_doodle);
                setOpSubDisplay(OP_SUB_DOODLE);
                break;
            case MOSAIC:
                mModeGroup.check(R.id.rb_mosaic);
                setOpSubDisplay(OP_SUB_MOSAIC);
                break;
            case NONE:
                mModeGroup.clearCheck();
                setOpSubDisplay(OP_HIDE);
                break;
        }
    }

    public void onTextModeClick() {
        if (mTextDialog == null) {
            mTextDialog = new IMGTextEditDialog(this, this);
            mTextDialog.setOnShowListener(this);
            mTextDialog.setOnDismissListener(this);
        }
        mTextDialog.show();
    }

    @Override
    public final void onCheckedChanged(RadioGroup group, int checkedId) {
        if (mColorGroup.isCheckMosaic()) {
            mImgView.setMode(IMGMode.MOSAIC);
        } else {
            mImgView.setMode(IMGMode.DOODLE);
            onColorChanged(mColorGroup.getCheckColor());
        }
    }

    public void setOpDisplay(int op) {
        if (op >= 0) {
            mOpSwitcher.setDisplayedChild(op);
        }
    }

    public void setOpSubDisplay(int opSub) {
        if (opSub < 0) {
            mLayoutOpSub.setVisibility(View.GONE);
        } else {
            mLayoutOpSub.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onShow(DialogInterface dialog) {
        mOpSwitcher.setVisibility(View.GONE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { //11及以上底部会在软键盘上边显示
            KeyboardUtils.registerSoftInputChangedListener(getWindow(), new KeyboardUtils.OnSoftInputChangedListener() {
                @Override
                public void onSoftInputChanged(final int height) {
                    mTextDialog.getColorGroup().setPadding(0,0, 0, height);
                }
            });
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        mOpSwitcher.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        }
    }

    public abstract Bitmap getBitmap();

    public abstract void onModeClick(IMGMode mode);

    public abstract void onUndoClick();

    public abstract void onCancelClick();

    public abstract void onDoneClick();

    public abstract void onCancelClipClick();

    public abstract void onDoneClipClick();

    public abstract void onResetClipClick();

    public abstract void onRotateClipClick();

    public abstract void onColorChanged(int checkedColor);

    @Override
    public abstract void onText(IMGText text);
}
